package org.jeecg.modules.wmhb.controller;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.common.system.vo.SelectTreeModel;
import org.jeecg.modules.wmhb.entity.WmTask;
import org.jeecg.modules.wmhb.entity.WmTaskBom;
import org.jeecg.modules.wmhb.service.IWmTaskBomService;
import org.jeecg.modules.wmhb.service.IWmTaskService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.wmhb.dto.req.HjdBomReqDto;
import org.jeecg.modules.wmhb.dto.res.HjdBomResDto;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.apache.shiro.authz.annotation.RequiresPermissions;

/**
 * @Description: 任务
 * @Author: jeecg-boot
 * @Date: 2025-09-30
 * @Version: V1.0
 */
@Tag(name = "任务")
@RestController
@RequestMapping("/wmhb/wmTask")
@Slf4j
public class WmTaskController extends JeecgController<WmTask, IWmTaskService> {
    @Autowired
    private IWmTaskService wmTaskService;
    @Autowired
    private IWmTaskBomService wmTaskBomService;

    /**
     * 分页列表查询
     *
     * @param wmTask
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "任务-分页列表查询")
    @Operation(summary = "任务-分页列表查询")
    @GetMapping(value = "/rootList")
    public Result<IPage<WmTask>> queryPageList(WmTask wmTask,
                                               @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                               @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                               HttpServletRequest req) {
        String hasQuery = req.getParameter("hasQuery");
        if (hasQuery != null && "true".equals(hasQuery)) {
            QueryWrapper<WmTask> queryWrapper = QueryGenerator.initQueryWrapper(wmTask, req.getParameterMap());
            List<WmTask> list = wmTaskService.queryTreeListNoPage(queryWrapper);
            IPage<WmTask> pageList = new Page<>(1, 10, list.size());
            pageList.setRecords(list);
            return Result.OK(pageList);
        } else {
            String parentId = wmTask.getPid();
            if (oConvertUtils.isEmpty(parentId)) {
                parentId = "0";
            }
            wmTask.setPid(null);
            QueryWrapper<WmTask> queryWrapper = QueryGenerator.initQueryWrapper(wmTask, req.getParameterMap());
            // 使用 eq 防止模糊查询
            queryWrapper.eq("pid", parentId);
            Page<WmTask> page = new Page<WmTask>(pageNo, pageSize);
            IPage<WmTask> pageList = wmTaskService.page(page, queryWrapper);
            return Result.OK(pageList);
        }
    }

    /**
     * 【vue3专用】加载节点的子数据
     *
     * @param pid
     * @return
     */
    @RequestMapping(value = "/loadTreeChildren", method = RequestMethod.GET)
    public Result<List<SelectTreeModel>> loadTreeChildren(@RequestParam(name = "pid") String pid) {
        Result<List<SelectTreeModel>> result = new Result<>();
        try {
            List<SelectTreeModel> ls = wmTaskService.queryListByPid(pid);
            result.setResult(ls);
            result.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            result.setMessage(e.getMessage());
            result.setSuccess(false);
        }
        return result;
    }

    /**
     * 【vue3专用】加载一级节点/如果是同步 则所有数据
     *
     * @param async
     * @param pcode
     * @return
     */
    @RequestMapping(value = "/loadTreeRoot", method = RequestMethod.GET)
    public Result<List<SelectTreeModel>> loadTreeRoot(@RequestParam(name = "async") Boolean async, @RequestParam(name = "pcode") String pcode) {
        Result<List<SelectTreeModel>> result = new Result<>();
        try {
            List<SelectTreeModel> ls = wmTaskService.queryListByCode(pcode);
            if (!async) {
                loadAllChildren(ls);
            }
            result.setResult(ls);
            result.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            result.setMessage(e.getMessage());
            result.setSuccess(false);
        }
        return result;
    }

    /**
     * 【vue3专用】递归求子节点 同步加载用到
     *
     * @param ls
     */
    private void loadAllChildren(List<SelectTreeModel> ls) {
        for (SelectTreeModel tsm : ls) {
            List<SelectTreeModel> temp = wmTaskService.queryListByPid(tsm.getKey());
            if (temp != null && temp.size() > 0) {
                tsm.setChildren(temp);
                loadAllChildren(temp);
            }
        }
    }

    /**
     * 获取子数据
     *
     * @param wmTask
     * @param req
     * @return
     */
    //@AutoLog(value = "任务-获取子数据")
    @Operation(summary = "任务-获取子数据")
    @GetMapping(value = "/childList")
    public Result<IPage<WmTask>> queryPageList(WmTask wmTask, HttpServletRequest req) {
        QueryWrapper<WmTask> queryWrapper = QueryGenerator.initQueryWrapper(wmTask, req.getParameterMap());
        List<WmTask> list = wmTaskService.list(queryWrapper);
        IPage<WmTask> pageList = new Page<>(1, 10, list.size());
        pageList.setRecords(list);
        return Result.OK(pageList);
    }

    /**
     * 批量查询子节点
     *
     * @param parentIds 父ID（多个采用半角逗号分割）
     * @param parentIds
     * @return 返回 IPage
     * @return
     */
    //@AutoLog(value = "任务-批量获取子数据")
    @Operation(summary = "任务-批量获取子数据")
    @GetMapping("/getChildListBatch")
    public Result getChildListBatch(@RequestParam("parentIds") String parentIds) {
        try {
            QueryWrapper<WmTask> queryWrapper = new QueryWrapper<>();
            List<String> parentIdList = Arrays.asList(parentIds.split(","));
            queryWrapper.in("pid", parentIdList);
            List<WmTask> list = wmTaskService.list(queryWrapper);
            IPage<WmTask> pageList = new Page<>(1, 10, list.size());
            pageList.setRecords(list);
            return Result.OK(pageList);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error("批量查询子节点失败：" + e.getMessage());
        }
    }

    /**
     * 添加
     *
     * @param wmTask
     * @return
     */
    @AutoLog(value = "任务-添加")
    @Operation(summary = "任务-添加")
    @RequiresPermissions("wmhb:wm_task:add")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody WmTask wmTask) {
        wmTaskService.addWmTask(wmTask);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param wmTask
     * @return
     */
    @AutoLog(value = "任务-编辑")
    @Operation(summary = "任务-编辑")
    @RequiresPermissions("wmhb:wm_task:edit")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody WmTask wmTask) {
        wmTaskService.updateWmTask(wmTask);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "任务-通过id删除")
    @Operation(summary = "任务-通过id删除")
    @RequiresPermissions("wmhb:wm_task:delete")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        wmTaskService.deleteWmTask(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "任务-批量删除")
    @Operation(summary = "任务-批量删除")
    @RequiresPermissions("wmhb:wm_task:deleteBatch")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.wmTaskService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功！");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "任务-通过id查询")
    @Operation(summary = "任务-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<WmTask> queryById(@RequestParam(name = "id", required = true) String id) {
        WmTask wmTask = wmTaskService.getById(id);
        if (wmTask == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(wmTask);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param wmTask
     */
    @RequiresPermissions("wmhb:wm_task:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, WmTask wmTask) {
        return super.exportXls(request, wmTask, WmTask.class, "任务");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequiresPermissions("wmhb:wm_task:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, WmTask.class);
    }

    /**
     * 转换
     *
     * @param ids
     * @param userId
     * @param memo
     * @return
     */
    @AutoLog(value = "任务-转办")
    @Operation(summary = "任务-转办")
    //@RequiresPermissions("wmhb:wm_task:transfer")
    @PostMapping(value = "/transfer")
    public Result<String> transfer(@RequestParam(name = "ids", required = true) String ids, @RequestParam(name = "userId", required = true) String userId, @RequestParam(name = "memo", required = false) String memo) {
        List<String> idList = Arrays.asList(ids.split(","));
        wmTaskService.transferTask(idList, userId, memo);
        return Result.OK("操作成功！");
    }

    /**
     * 设置报料人员
     *
     * @param ids
     * @param userId
     * @return
     */
    @AutoLog(value = "任务-设置报料人员")
    @Operation(summary = "任务-设置报料人员")
    //@RequiresPermissions("wmhb:wm_task:setWantedUser")
    @PostMapping(value = "/setWantedUser")
    public Result<String> setWantedUser(@RequestParam(name = "ids", required = true) String ids, @RequestParam(name = "userId", required = true) String userId) {
        List<String> idList = Arrays.asList(ids.split(","));
        wmTaskService.setWantedUser(idList, userId);
        return Result.OK("操作成功！");
    }

    /**
     * 设置核减人员
     *
     * @param ids
     * @param userId
     * @return
     */
    @AutoLog(value = "任务-设置核减人员")
    @Operation(summary = "任务-设置核减人员")
    //@RequiresPermissions("wmhb:wm_task:setStorageUser")
    @PostMapping(value = "/setStorageUser")
    public Result<String> setStorageUser(@RequestParam(name = "ids", required = true) String ids, @RequestParam(name = "userId", required = true) String userId) {
        List<String> idList = Arrays.asList(ids.split(","));
        wmTaskService.setStorageUser(idList, userId);
        return Result.OK("操作成功！");
    }

    /**
     * 合并导出报料BOM
     *
     * @param request
     * @param ids
     */
    //@RequiresPermissions("wmhb:wm_task:exportApplyXls")
    @RequestMapping(value = "/exportApplyXls")
    @Operation(summary = "任务-合并导出报料BOM")
    public ModelAndView exportApplyXls(HttpServletRequest request, @RequestParam(name = "ids", required = true) String ids) {
        List<String> taskIdList = Arrays.asList(ids.split(","));
        List<WmTaskBom> wmTaskBomList = wmTaskBomService.applyBomList(taskIdList);//报料BOM列表
        if (wmTaskBomList.isEmpty()) {
            throw new RuntimeException("当前任务没有物料");
        }
        return wmTaskBomService.exportBomExcel(request, wmTaskBomList);
    }

    /**
     * 通过excel导入核减单数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequiresPermissions("wmhb:wm_task:importApplyExcel")
    @RequestMapping(value = "/importApplyExcel", method = RequestMethod.POST)
    @Operation(summary = "任务-导入核减单数据")
    @Transactional
    public Result<?> importApplyExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            // 获取上传文件对象
            MultipartFile file = entity.getValue();
            Integer sheetNum = 1;
            Workbook workbook = null;
            try {
                workbook = WorkbookFactory.create(file.getInputStream());
                sheetNum = workbook.getNumberOfSheets();//读取sheet的数量
            } catch (Exception e) {
                throw new RuntimeException(e.getMessage());
            }

            ImportParams params = new ImportParams();
            params.setStartSheetIndex(0); //从第几个sheet页开始读取
            params.setSheetNum(sheetNum); //读取几个sheet页
            params.setTitleRows(0);       //标题行数
            params.setHeadRows(1);        //头部行数
            params.setNeedSave(false);    //是否保存文件
            try {
                List<HjdBomReqDto> list = ExcelImportUtil.importExcel(file.getInputStream(), HjdBomReqDto.class, params);
                HjdBomResDto hjdBomResDto = wmTaskBomService.uploadHjdBom(list);
                return Result.ok(hjdBomResDto);
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                throw new RuntimeException(e.getMessage());
            } finally {
                try {
                    workbook.close();
                    file.getInputStream().close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.error("文件导入失败！");
    }

    /**
     * 完成核减 生成采购订单
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "任务-完成核减")
    @Operation(summary = "任务-完成核减")
    //@RequiresPermissions("wmhb:wm_task:finishStorage")
    @PostMapping(value = "/finishStorage")
    public Result<String> finishStorage(@RequestParam(name = "ids", required = true) String ids) {
        List<String> idList = Arrays.asList(ids.split(","));
        wmTaskService.finishStorage(idList);
        return Result.OK("操作成功！");
    }

}
